package com.lyfx.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.annotation.JsonAlias;
import com.lyfx.common.to.es.CourseModel;
import com.lyfx.search.config.ElasticSearchConfig;
import com.lyfx.search.contant.Esconstant;
import com.lyfx.search.service.CourseSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lsy
 * @create 2020-07-25-13:11
 */
@Service
@Slf4j
public class CourseSaveServiceImpl implements CourseSaveService {

    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Override
    public boolean courseStatusUp(List<CourseModel> courseModel){
        //保存到es中
        //1.建立索引,建立映射关系
        //2.保存索引
        BulkRequest bulkRequest = new BulkRequest();
        int i = 0;
        for (CourseModel model : courseModel) {
            IndexRequest indexRequest = new IndexRequest(Esconstant.COURSE_INDEX);
            indexRequest.id((Esconstant.PRE_INDEX+i++)+model.getCourseId().toString());
            String s = JSON.toJSONString(model);
            indexRequest.source(s, XContentType.JSON);

            bulkRequest.add(indexRequest);
        }
        BulkResponse bulk = null;
        try {
            bulk = restHighLevelClient.bulk(bulkRequest, ElasticSearchConfig.COMMON_OPTIONS);
            List<String> collect = Arrays.stream(bulk.getItems()).map(item -> {
                return item.getId();
            }).collect(Collectors.toList());
            log.info("上传{}号课程成功",collect);
            return !bulk.hasFailures();
        } catch (IOException e) {
            List<String> collect = Arrays.stream(bulk.getItems()).map(item -> {
                return item.getId();
            }).collect(Collectors.toList());
            log.error("上传{}号课程失败,{}",collect,e.getMessage());
        }
        return bulk.hasFailures();
    }
}
